<?php

namespace app\api\controller;

use alipay\aop\AopClient;
use app\common\controller\Api;
use app\common\library\Pay;
use app\common\model\campsite\Order as CampsiteOrder;
use app\common\model\fittings\Order as FittingsOrder;
use app\common\model\lease\Order as LeaseOrder;
use app\common\model\modify\Order as ModifyOrder;
use app\common\model\User;
use think\Db;
use think\Log;

/**
 * 回调接口
 */
class Notify extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];


    /**
     * Notes: 信用卡回调
     */
    public function notifyCredit()
    {
        \Stripe\Stripe::setApiKey('pk_test_51NWKdBF5YWjDtpHf36MEvsuuz9XWhaZPM0u8mrm0OkN0zpoMB0dHiWxw0A7dfK5KJvp3Z5YCyrB1bdpqEPLBWkbY004nAoAFag');
        $payload = @file_get_contents('php://input');
        $event = null;
        Log::write('信用卡回调数据：' . $payload);
        try {
            $event = \Stripe\Event::constructFrom(
                json_decode($payload, true)
            );
        } catch (\UnexpectedValueException $e) {
            // Invalid payload
            Log::write('信用卡回调错误：' . json_encode($e, JSON_UNESCAPED_UNICODE));
            http_response_code(400);
            exit();
        }
        Log::write('信用卡回调验证：' . json_encode($event, JSON_UNESCAPED_UNICODE));
        // Handle the event
        switch ($event->type) {
            case 'charge.succeeded':
                $succeeded = $event->data->object;
                if ($succeeded->status == 'succeeded') {
                    $id = $succeeded->id;
                    $card_order = Db::name('card_order')->where('transaction_id', $id)->where('pay_status', 0)->find();
                    $course_order = Db::name('course_order')->where('transaction_id', $id)->where('pay_status', 0)->find();
                    $order = Db::name('order')->where('transaction_id', $id)->where('pay_status', 0)->find();
                    if ($card_order) {
                        CardItemLogic::yue($card_order['id']);
                        $data =  Db::name('card_item')
                            ->where(['is_del' => 0])
                            ->where(['id' => $card_order['card_id']])
                            ->where(['static' => 1])
                            ->find();
                        $data_en =  Db::name('card_item_en')
                            ->where(['is_del' => 0])
                            ->where(['id' => $card_order['card_id']])
                            ->where(['static' => 1])
                            ->find();
                        $json = [
                            'zh-cn' => $data,
                            'en-us' => $data_en,
                        ];
                        CardItemLogic::addUserCard($card_order['user_id'], $data, $json);
                        if ($card_order['commission'] != 3) {
                            $row =  AccountLogLogic::commission($card_order['user_id'], $card_order['id']);
                        }
                    }
                    if ($course_order) {
                        Db::name('course_order')->where('id', $course_order['id'])->update(['pay_status' => 1, 'pay_time' => time()]);
                        $cur_info = Db::name('curriculum')->where('id', $course_order['cur_id'])->where('is_del', 0)->find();
                        Db::name('schedule')->where('id', $cur_info['s_id'])->inc('sales', 1)->update();
                        Db::name('schedule_en')->where('id', $cur_info['s_id'])->inc('sales', 1)->update();
                        Db::name('curriculum')->where('id', $course_order['cur_id'])->inc(['count' => 1])->update();
                        $user = Db::name('user')->where('id', $course_order['user_id'])->find();
                        if (isset($user['mobile']) && $user['mobile']) {
                            $content = "【Wfitclub】Dear " . $user['nickname'] . ", your appointment is successful.";
                            SmsLogic::sendSms($user['mobile'], $content);
                        }
                    }
                    if ($order) {
                        if (!$order || $order['pay_status'] >= Pay::ISPAID) {
                            return true;
                        }
                        PayNotifyLogic::handle('order', $order['order_sn'], []);
                    }
                }
                break;
        }
        return true;
    }
    /**
     * 微信回调
     */
    public function wechatNotify()
    {
        $data = file_get_contents('php://input');
        Log::write('验证支付：' . $data);
        // $data='{"id":"7f769483-ba0f-5e34-bc3b-299637f52e70","create_time":"2023-07-19T18:17:51+08:00","resource_type":"encrypt-resource","event_type":"TRANSACTION.SUCCESS","summary":"支付成功","resource":{"original_type":"transaction","algorithm":"AEAD_AES_256_GCM","ciphertext":"M51+nO17THBak9hnDcmBB2wCRgSMfFDQTDPpHzkVHs0Y9g2MZmb7dH6I2iPs9nT3TO2MdGaRi1/pbhcDqr6ip6TQXIzCtHA9IDsznh6kcnx+FKyCkZmepTaioamfo3vNYxTDWb+IW8EFzE6MkL1nA8pPv0Cu35/VCJ3E8a4yd6TOlAKda7mndHXNTd5v4DQNVsAMZ7GMHIcC1GlFmKlTFFtLAnkp5JBtbsOgh6EFX/Ila8DcSnseCFBMVQvJ7cT00uUbWzp0pcTz2vl2LgQYkJaO5js2iITI9E/PKJBm+WO0YG4qzDgaCwbOhi0DaRtt8uIRyhe7zV2ygM5KHc7js5FToV3sO52QTTBVidAaNG1I27G1LNk/se3+VDfvkhZCM29s2hUrRsbxIbFp6IrbWwcmndL9iRjsCpWrRBHB19sjhkpi0l0v1Fw6rzeBMnqhbZ6iHK1fxX2kHMkzKZcre0/nlNpz65WYJnKDgL+81v5aAXAfUgS5rqXrDm6WrCrlOz04cpnhqZwIsinxwjy/UzOeby56LK2fXFMqMP7UDVGQh6BRPdU/Ht8b+I1xFiKt0wOVwi0gXCc=","associated_data":"transaction","nonce":"8fBfKfrycCL2"}}';
        $data = json_decode($data, true);
        $nonceStr = $data['resource']['nonce'];
        $associatedData = $data['resource']['associated_data'];
        $ciphertext = $data['resource']['ciphertext'];
        $ciphertext = base64_decode($ciphertext);
        // php>7.1,为了使用这个扩展，你必须将extension=php_sodium.dll添加到php.ini
        if (function_exists('\sodium_crypto_aead_aes256gcm_is_available') && \sodium_crypto_aead_aes256gcm_is_available()) {
            // $APIv3_KEY就是在商户平台后端设置是APIv3秘钥
            $orderData = \sodium_crypto_aead_aes256gcm_decrypt($ciphertext, $associatedData, $nonceStr, 'QbyyrkXYWbwSVT3kw3FwBj1xv9b8rLLu');
            Log::write('支付成功：' . $orderData);
            // $orderData ='{"mchid":"1635149963","appid":"wx1c2ddbc154bece77","out_trade_no":"XX202212081422119380","transaction_id":"4200001642202212085961916819","trade_type":"JSAPI","trade_state":"SUCCESS","trade_state_desc":"支付成功","bank_type":"OTHERS","attach":"order","success_time":"2022-12-08T14:22:21+08:00","payer":{"openid":"of5sB5sZ4gSQQM6wY6h6KQp1hiWA"},"amount":{"total":1,"payer_total":1,"currency":"CNY","payer_currency":"CNY"}}';
            // Db::name('pay_log')->insert(['data' => $orderData]);
            $orderData = json_decode($orderData, true);
            if ($orderData['trade_state'] == 'SUCCESS') {
                $order_sn = $orderData['out_trade_no']; //商户订单号
                $transaction_id = $orderData['transaction_id']; //微信订单号
                $attach = $orderData['attach']; //微信订单号
                $time = time();
                // 启动事务
                Db::startTrans();
                try {
                    /*业务处理*/
                    switch ($attach) {
                        case 'modify':
                            $order = ModifyOrder::get(['sn' => $order_sn, 'status' => '0']);
                            $order->status = '1';
                            $order->paytime = $time;
                            $order->transaction_id = $transaction_id;
                            $order->save();
                            break;
                        case 'campsite':
                            $order = CampsiteOrder::get(['sn' => $order_sn, 'status' => '0']);
                            $order->status = '1';
                            $order->paytime = $time;
                            $order->transaction_id = $transaction_id;
                            $order->save();
                            break;
                        case 'lease':
                            $order = LeaseOrder::get(['sn' => $order_sn, 'status' => '0']);
                            $order->status = '1';
                            $order->paytime = $time;
                            $order->transaction_id = $transaction_id;
                            $order->save();
                            break;
                        case 'fittings':
                            $order = FittingsOrder::get(['sn' => $order_sn, 'status' => '0']);
                            $order->status = '1';
                            $order->paytime = $time;
                            $order->transaction_id = $transaction_id;
                            $order->save();
                            break;
                    }
                    Db::commit();
                    //应答微信支付已处理该订单的通知
                    return 'SUCCESS';
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    Log::error($e->getMessage());
                    return $e->getMessage();
                }
            }
        }
    }

    //退款回调地址
    public static function refundNotify()
    {
        $notifiedData = file_get_contents('php://input');
        $data = json_decode($notifiedData, true);
        Log::write('验证退款：' . $data);

        $nonceStr = $data['resource']['nonce'];
        $associatedData = $data['resource']['associated_data'];
        $ciphertext = $data['resource']['ciphertext'];
        $ciphertext = base64_decode($ciphertext);
        //php>7.1,为了使用这个扩展，你必须将extension=php_sodium.dll添加到php.ini
        if (function_exists('\sodium_crypto_aead_aes256gcm_is_available') && \sodium_crypto_aead_aes256gcm_is_available()) {
            //$APIv3_KEY就是在商户平台后端设置是APIv3秘钥
            $orderData = \sodium_crypto_aead_aes256gcm_decrypt($ciphertext, $associatedData, $nonceStr, 'QbyyrkXYWbwSVT3kw3FwBj1xv9b8rLLu');
            $orderData = json_decode($orderData, true);
            Log::write('退款成功：' . $orderData);

            if ($orderData['refund_status'] == 'SUCCESS') {
                $transaction_id = $orderData['transaction_id']; //退款单号
                $order = FittingsOrder::get(['transaction_id' => $transaction_id]);
                if ($order->settlement == 0) {
                    return json(['code' => 'SUCCESS', 'message' => '成功']);
                }
                $user = User::get($order->user_id);
                if ($order->p_id) {
                    $puser = User::get($order->p_id);
                    if ($puser->total_interests <= $order->p_interests) {
                        $puser->total_interests = 0;
                    } else {
                        $puser->setDec('total_interests', $order->p_interests);
                    }
                }
                //分红金额扣除
                if ($order->dividend > 0) {
                    //扣除可分红金额
                    if ($user->use_dividend <= $order->dividend) {
                        $user->use_dividend = 0;
                    } else {
                        $user->setDec('use_dividend', $order->dividend);
                    }
                    //扣除合计分红金额
                    if ($user->total_dividend <= $order->dividend) {
                        $user->total_dividend = 0;
                    } else {
                        $user->setDec('total_dividend', $order->dividend);
                    }
                }
                //权益值扣除
                if ($order->interests > 0) {
                    if ($user->total_interests <= $order->interests) {
                        $user->setDec('total_interests', $order->total_interests);
                    } else {
                        $user->setDec('total_interests', $order->interests);
                    }
                }
                //累计消费扣除
                if ($order->pay_money > 0) {
                    $user->setDec('consumption', $order->pay_money);
                }

                //上级累计权益值扣除
                if ($order->p_id > 0) {
                    $puser = User::get($order->p_id);
                    if ($order->p_interests >= $puser->total_interests) {
                        $puser->setDec('total_interests', $order->total_interests);
                    } else {
                        $puser->setDec('total_interests', $order->p_interests);
                    }
                }


                // if ($order->interests > 0) {
                //     if ($order->interests >= $user->total_interests) {
                //         $order->refund_interests = $user->total_interests;
                //     }
                //     if ($order->interests < $user->total_interests) {
                //         $order->refund_interests = $order->interests;
                //     }
                //     $user->use_dividend = $order->refund_interests;

                // }
                $order->save();
                $user->save();
                // $res = Order::where('transaction_id',  $transaction_id)->update(['status' => 6, 'returntime' => time()]);


                /*业务处理*/
                return json(['code' => 'SUCCESS', 'message' => '成功']);
            }
        }
    }
}
